<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never" style="margin:-10px">
        <questions-choice>
          <!-- 插入到 left 插槽位置 -->
          <template #left>
            <span>说明：目前支持学科和关键字条件筛选</span>
          </template>
          <!-- 插入到 right 插槽位置 -->
          <template #right>
            <el-button type="success" size="small" @click="$router.push('new')"><i class="el-icon-edit"></i>新增试题</el-button>
          </template>
        </questions-choice>
        <!-- 插入表单选择 -->
        <search-form @submit-search="submitSearch"></search-form>
        <div class="elTabs">
          <el-tabs v-model="tabsSelect" type="card" @tab-click="handleClick">
            <el-tab-pane label="全部" name="all" ></el-tab-pane>
            <el-tab-pane label="待审核" name="0"></el-tab-pane>
            <el-tab-pane label="已审核" name="1"></el-tab-pane>
            <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="elAlert">
          <el-alert
            :title="showTitle"
            type="info"
            show-icon>
          </el-alert>
        </div>
        <div class="elTable">
          <el-table
            :data="tableData"
            style="width: 100%">
            <el-table-column
              prop="number"
              label="试题编号"
              width="150">
            </el-table-column>
            <el-table-column
              prop="subject"
              label="学科"
              width="120">
            </el-table-column>
            <el-table-column
              prop="catalog"
              label="目录"
              width="120">
            </el-table-column>
            <el-table-column
              label="题型"
              prop="questionType"
              width="120">
              <template #default={row}>
                {{formatQuestionType(questionType,row.questionType)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="question"
              label="题干"
              width="300">
              <template #default={row}>
                {{matchReg(row.question)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="addDate"
              label="录入时间"
              width="120">
              <template #default={row}>
                {{formatDate(row.addDate)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="difficulty"
              label="难度"
              width="120">
              <template #default={row}>
                {{formatQuestionType(difficulty,row.difficulty)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="creator"
              label="录入人"
              width="120">
            </el-table-column>
            <el-table-column
              prop="chkState"
              label="审核状态"
              width="120">
              <template #default={row}>
                {{chkState[row.chkState]}}
              </template>
            </el-table-column>
            <el-table-column
              prop="chkRemarks"
              label="审核意见"
              width="120">
            </el-table-column>
            <el-table-column
              prop="chkUser"
              label="审核人"
              width="120">
            </el-table-column>
            <el-table-column
              prop="publishState"
              label="发布状态"
              width="120">
              <template #default={row}>
                {{row.chkState === 0 || row.chkState === 2 ? "待发布" :row.publishState === 0 ? '已下架' :'已发布'}}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="200">
              <template #default="{row}">
                <el-button @click="dialogOpen(row.id)" type="text" size="small">预览</el-button>
                <el-button type="text" size="small" :disabled="row.chkState !== 0" @click="auditeDiaOpen(row.id)">审核</el-button>
                <el-button type="text" size="small" @click='jumpQuestionsNew(row.id)' :disabled="row.publishState === 1">修改</el-button>
                <el-button type="text" size="small" @click="toJumpDown(row)">{{row.publishState === 0 ?'上架' : '下架'}}</el-button>
                <el-button type="text" size="small" :disabled="row.publishState === 1" @click="deleteQuestionChoice(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-row type="flex" justify="end">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="pagesize"
              layout="prev, pager, next, sizes, jumper"
              :total="counts">
            </el-pagination>
          </el-row>
        </div>
      </el-card>
    </div>
    <questions-check :check-visible="checkVisible" @check-close="checkClose" :checkId="checkId" @get-question-choice="getQuestion"></questions-check>
    <questions-preview :dialogVisible='dialogVisible' @dialog-close="dialogClose" :questionsId="questionsId"></questions-preview>
  </div>
</template>

<script>
// import MyCity from './companys/citys.vue'
// import {simple as subSimple} from "@/api/hmmm/subjects"
// import {simple as tagsSimple} from "@/api/hmmm/tags"
// import {simple as usersSimple } from "@/api/base/users";
// import {simple} from "@/api/hmmm/directorys"
import SearchForm from "../components/search-form.vue";
import { questionType, difficulty, direction, publishType } from "@/api/hmmm/constants";
import { choice, choicePublish, remove } from "@/api/hmmm/questions";
import QuestionsCheck from "../components/questions-check.vue";
import QuestionsPreview from "../components/questions-preview.vue";
import dayjs from 'dayjs'

  export default {
    data() {
      return {
        questionType: questionType,
        difficulty: difficulty,
        direction: direction,
        publishType:publishType,
        tabsSelect:'all',
        tableData: [],
        // 分页
        counts:0,
        page:1,
        pagesize:5,
        // 数据一共
        showTitle:'',
        chkState:{
          1:"已审核",
          0:"待审核",
          2:"已拒绝"
        },
        dialogVisible:false,
        questionsId:0,
        // questions-check的visible
        checkVisible:false,
        checkId:0,
      }
    },
    components: {
      QuestionsCheck,
      QuestionsPreview,
      SearchForm
    },
    methods: {
      // 预览的弹窗
      dialogOpen(id){
        this.dialogVisible = true
        this.questionsId = id
      },
      dialogClose(){
        this.dialogVisible = false
      },
      // 审核的弹窗打开以及关闭
      auditeDiaOpen(id){
        this.checkVisible = true
        this.checkId = id
      },
      checkClose(){
        this.checkVisible = false
        // 需要进行check刷新的操作，这个需要做
      },
      getQuestion(){
        this.getQuestionChoice({page:this.page,pagesize:this.pagesize})
      },
      // 到此处审核功能已完成
      // 每页显示的条数
      // 跳转到试题录入页面
      jumpQuestionsNew(id){
        this.$router.push({
          path:'/questions/new',
          query:{
            id
          }
        })
      },
      // 上架传1
      toJumpDown(row){
        this.$confirm(`您确认${row.publishState === 0 ?'上架' : '下架'}这道题目吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        const publish = row.publishState ^ 1
        await choicePublish({...row,publishState:publish})
        this.$message({
            type: 'success',
            message: `${row.publishState === 0 ?'上架' : '下架'}成功!`
          });
        this.getQuestionChoice({page:this.page,pagesize:this.pagesize})
        }) 
      },
      // 删除操作
      deleteQuestionChoice(id){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await remove({id})
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getQuestionChoice({page:this.page,pagesize:this.pagesize})
        }) 
      },
      // 分页功能
      handleSizeChange(val){
        this.pagesize = val
        this.page = 1
        this.getQuestionChoice({page:this.page,pagesize:this.pagesize})
      },
      handleCurrentChange(val){
        this.page = val
        this.getQuestionChoice({page:this.page,pagesize:this.pagesize})
      },
      // 显示表格的数据
      async getQuestionChoice(data){
        const res = await choice(data)
        this.tableData = res.data.items
        // console.log(this.tableData);
        this.counts = res.data.counts
        this.page = +res.data.page
        this.pagesize = +res.data.pagesize
        this.showTitle= `数据一共${this.counts}条`
      },
      // 封装的转换数据的方法
      formatQuestionType(state,value){
        const arr = state.filter(item =>{
           return item.value == value
        })
        // console.log(arr[0].label);
        if (arr.length === 0) {
          return ''
        }
        return arr[0].label
      },
      // html转换的方法
      matchReg(str){

        let reg=/<\/?.+?\/?>/g;

        return str.replace(reg,'')
       },
      formatDate(value) {
        return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    },
    // tabs点击转换
      handleClick(tab){
        if (tab.name === 'all') {
          this.getQuestionChoice({page:1,pagesize:this.pagesize})
        }else if(tab.name === '1'){
          this.getQuestionChoice({page:1,pagesize:this.pagesize,chkState:1})
        }else if(tab.name === '2'){
          this.getQuestionChoice({page:1,pagesize:this.pagesize,chkState:2})
        }else{
          this.getQuestionChoice({page:1,pagesize:this.pagesize,chkState:0})
        }
      },
      submitSearch(data){
        this.getQuestionChoice({page:this.page,pagesize:this.pagesize,...this.filterParams(data)})
      },
      // 如果对象的每一项为空则删除该项
      filterParams(obj){
        let _newPar = {};
        for (let key in obj) {
            //如果对象属性的值不为空，就保存该属性（，如果属性的值为0，保存该属性。如果属性的值全部是空格，属于为空。）
            if ((obj[key] === 0 || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
                //记录属性
                _newPar[key] = obj[key];
            }
        }
        //返回对象
        return _newPar;
      }
    },
    created(){
      // this.getSubjectOption()
      this.getQuestionChoice({page:this.page,pagesize:this.pagesize})
    }
  }
</script>

<style lang="scss" scoped>
::v-deep .left {
      font-size: 12px;
      color: pink;
}
.form {
  margin-top:20px ;
}
</style>
